
import 'package:flutter/material.dart';

class ScrollListenerTest extends StatefulWidget {

  @override
  _ScrollListenerTestState createState() => _ScrollListenerTestState();
}

class _ScrollListenerTestState extends State<ScrollListenerTest> {

  final ScrollController _controller = new ScrollController();
  bool isEnd = false;
  double offset = 0;
  String notify = "";

  @override
  void initState() {
    super.initState();
    _controller.addListener((){
      setState(() {
        offset = _controller.offset;
        isEnd = _controller.position.pixels == _controller.position.maxScrollExtent;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('滑动监听'),
      ),
      body: Container(
        child: NotificationListener(
          onNotification: (notification){
            String notify = "";
            if(notification is ScrollEndNotification){
              notify = "ScrollEnd";
            }else if(notification is ScrollStartNotification){
              notify = "ScrollState";
            }else if(notification is UserScrollNotification){
              notify = "UserScroll";
            }else if(notification is ScrollUpdateNotification){
              notify = "ScrollUpdate";
            }
            setState(() {
              this.notify = notify;
            });
            return false;
          },
          child: ListView.builder(
              controller : _controller,
              itemCount: 100,
              itemBuilder: (context, index){
                return Card(
                  child: Container(
                    height: 60,
                    alignment: Alignment.centerLeft,
                    child: Text('Item${index+1}'),
                  ),
                );
              }),
        ),
      ),
      persistentFooterButtons: <Widget>[
        FlatButton(
          onPressed: (){
            _controller.animateTo(0, duration: Duration(seconds: 1), curve: Curves.easeIn);
          },
          child: Text('position : ${offset.floor()}'),
        ),
        Container(
          width: 0.3,
          height: 30.0,
        ),
        FlatButton(
          onPressed: (){},
          child: Text(notify),
        ),
        Visibility(
          visible: isEnd,
          child: FlatButton(
            onPressed: (){},
            child: Text('到达底部'),
          ),
        )
      ],
    );
  }
}
